import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


class Person {
    String name;
    int age;

    public Person() {}

    public Person(String name,int age) {
        this.name = name;
        this.age = age;
    }

    public void greet(String message) {
        System.out.println(name + " says: " + message);
    }
}
public class Test {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        // 获取class对象
        Class<?> clazz = Person.class;

        // 创建对象
        Constructor<?> constructor = clazz.getConstructor(String.class,int.class);
        Object person = constructor.newInstance("John",30);

        // 访问字段
        Field nameField = clazz.getDeclaredField("name");
        // 如果字段是私有的，将它设置为可访问
        nameField.setAccessible(true);
        System.out.println("Name: " + nameField.get(person));

        // 修改字段
        nameField.set(person,"Doe");
        System.out.println("Update Name: " + nameField.get(person));

        // 调用方法
        Method greetMethod = clazz.getMethod("greet", String.class);
        greetMethod.invoke(person,"world");
    }
}
